package service

import (
	"context"
	"errors"
	__ "user_service/basic/proto"
	"user_service/handler/dao"
	"user_service/handler/model"
	"user_service/pkg"
)

type Server struct {
	__.UnimplementedUserServer
}

// 用户注册
func (s *Server) RegisterReq(_ context.Context, in *__.RegisterReqReq) (*__.RegisterReqResp, error) {
	//判断用户是否存在
	var user model.User
	user.Mobile = in.Mobile
	if err := user.GetUserInfoByMobile(); err != nil {
		return nil, err
	}
	if user.Id != 0 {
		return nil, errors.New("用户已存在")
	}
	//注册
	user.Password = pkg.MD5(in.Password)
	if err := user.Create(); err != nil {
		return nil, err
	}
	//生成token
	token, err := pkg.TokenHandler(int64(user.Id))
	if err != nil {
		panic(err)
	}
	return &__.RegisterReqResp{
		Id:    int64(user.Id),
		Token: token,
	}, nil
}

// 用户收藏
func (s *Server) GoodLike(_ context.Context, in *__.GoodLikeReq) (*__.GoodLikeResp, error) {

	like := model.Like{
		UserId: uint(in.UserId),
		GoodId: uint(in.GoodId),
	}
	err := dao.Create(&like)
	if err != true {
		panic(err)
	}

	return &__.GoodLikeResp{
		Id: int64(like.Id),
	}, nil
}

// 用户收藏删除
func (s *Server) GoodRemove(_ context.Context, in *__.GoodRemoveReq) (*__.GoodRemoveResp, error) {

	like := model.Like{
		Id: uint(in.Id),
	}
	err := dao.Delete(&like)
	if err != true {
		panic(err)
	}

	return &__.GoodRemoveResp{}, nil
}
